﻿using System;
using System.Net.Mail;
using System.Web;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair.Account
{
    public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/Default.aspx");
            }

            pnl_RegistrationForm.Visible = false;
            pnl_RegistrationFormSubmitted.Visible = false;
            errorLabel.Text = "";

            if (!IsPostBack)
            {
                Session["CaptchaImageText"] = RngUtils.GetRandomNumberAsString(6);
            }

            if (Session["RegistrationFormSubmitted"] != null)
            {
                pnl_RegistrationFormSubmitted.Visible = true;
            }
            else
            {
                pnl_RegistrationForm.Visible = true;
                UserName.Focus();
                pnl_RegistrationForm.DefaultButton = "CreateUserButton";
            }
        }

        protected void CreateUserButtonClick(object sender, EventArgs e)
        {
            string captcha = Server.HtmlEncode(txt_Captcha.Text);
            if (captcha.Equals(Session["CaptchaImageText"].ToString()))
            {
                bool mailValid = true;
                MailAddress mail = null;
                try
                {
                    mail = new MailAddress(Server.HtmlEncode(EmailText.Text));
                }
                catch(FormatException)
                {
                    mailValid = false;
                }

                UserService svc = new UserService();

                string user = Server.HtmlEncode(UserName.Text);
                string pass = Server.HtmlEncode(Password.Text);

                bool isTaken = svc.UserNameExists(user);

                if (isTaken)
                {
                    errorLabel.Text = "Naam is al bezet.";
                }
                else if(!mailValid)
                {
                    errorLabel.Text = "E-mail adres is onjuist.";
                }
                else
                {
                    bool mailExists = svc.UserEmailExists(mail.Address);
                    if (!mailExists)
                    {
                        string salt = EncryptionUtils.Salt();
                        string hash = EncryptionUtils.Hash(pass, salt);

                        User userToInsert = new User
                        {
                            Name = user,
                            Salt = salt,
                            Hash = hash,
                            Email = mail.Address,
                            DateRegistered = DateTime.Now,
                            IsActivated = false,
                            IsDeleted = false
                        };
                        svc.InsertUser(userToInsert);

                        string url = RngUtils.GetUrlString();
                        int userId = svc.GetUserByName(user).Id;

                        RegisterURL registerUrl = new RegisterURL
                        {
                            UserId = userId,
                            RegisterUrl = url,
                            DateGenerated = DateTime.Now
                        };
                        svc.InsertRegisterUrl(registerUrl);

                        Mailer mailer = new Mailer();
                        mailer.SendRegistrationMail(userToInsert, registerUrl);

                        Session["RegistrationFormSubmitted"] = true;
                        Response.Redirect("~/Account/Register.aspx");
                    }
                    else
                    {
                        errorLabel.Text = "E-mail adres is al bezet.";
                    }
                }
            }
            else
            {
                errorLabel.Text = "Bevestigingscode komt niet overeen.";   
            }
        }
    }
}
